define(['moment', 'module/system/service/WatchDogService'], function (moment) {
    return ['$scope', '$rootScope', '$filter', '$stateParams', 'config', 'MMWService', '$calculater', 'WatchDogService', '$timeout',
    function ($scope, $rootScope ,$filter, $stateParams, config, $MMWService, $calculater, $WatchDogService, $timeout) {
        $scope.refresh_frequency = 60; //預設60，範圍:10 ~ 300
        $scope.init = function(){
            $scope.area_no = '';
            $scope.area_dispaly = '';
            $scope.material_info_detail = [];
            $scope.filter = {
                cutting_time: "",
                mo_no: "",
                op_no: "",
                machine_no: "",
                position_no: "",
                material_no: "",
                material_plot: "",
                cutting_qty: "",
                cutting_labor: "",
                from_InventoryNo: "",
            };
            $scope.order_by_mode = {name: "", sort: false};
            $scope.PageConfig = {
                page: 0,
                total_page: 1,
                page_count: 25
            };
            if($stateParams.data){
                if($stateParams.data.area_no && $stateParams.data.area_no != ''){
                    $scope.area_no = $stateParams.data.area_no;
                }
            }
            if($scope.area_no != '')
                $WatchDogService.startWatch(dog, false);
        };

        $scope.back = function(){
            $scope.disconnection = false;
            $scope.final(function(){
                $scope.$root.changeProgram('home', true);
            });
        };

        $scope.final = function(callback){
            if(refresh_timer != undefined){
                $timeout.cancel(refresh_timer);
                refresh_timer = undefined;
            }
            $WatchDogService.stopWatch();
            if(typeof callback === 'function')
                callback();
        }

        //選擇區域
        $scope.loadAreaList = function(){
            $scope.$root.showQueryList({
                key:'page_no',
                header : [
                    {label: $filter('translate')('common.queryList.area_c'), code:'page_no'},
                    {label: $filter('translate')('common.queryList.area_n'), code:'page_name'}
                ],
                query: function(conditions, feedback){    
                    pageNumberInfoGet({page_mode : 'TBLSMDAREABASIS'}, function(data){
                        feedback(data);
                    });
                },
                selectCode:$scope.selectareaNo||'',
                confirm: function(selectItem, dialog){
                    $scope.area_no = selectItem.page_no;
                    $scope.area_display = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    dialog.hide();
                    dog.bark();
                }
            });
        };

        //更新頻率
        $scope.input_time = function(event){
            $WatchDogService.stopWatch();
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            $calculater.open(function(num, calcDialog){
                angular.element(target).removeClass('is-focus');
                if(+num < 10 || +num > 300){
                    $rootScope.showAlert($filter('translate')('F0202.msg.refresh_time_illegal'));
                }else{                            
                    calcDialog.hide();
                    dog.sleep = $scope.refresh_frequency = (+num);
                    $WatchDogService.startWatch(dog, false);
                }
            },
            function(calcDialog){
                angular.element(target).removeClass('is-focus');
                calcDialog.hide();
            },
            {
                title : $filter('translate')('F0202.calculater-title'),
                defaultNum : $scope.refresh_frequency,
                decimal : true
            });
        }

        $scope.confirm = function(item, event){
            item.type = '1';
            materialDashboardConfirmProcess(item, function(){
                dog.bark();
            });
        };

        $scope.getPages = function(list, PageConfig, filterItem){
            if(list){
                var temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if((item[key]+'').indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
                if ($scope.order_by_mode.name != "")
                    temp_list = $filter('orderBy')(temp_list, $scope.order_by_mode.name, $scope.order_by_mode.sort);
                if(PageConfig){
                    PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);
                    if(PageConfig.page >= PageConfig.total_page){
                        PageConfig.page = 0;
                    }
                    var index = PageConfig.page*PageConfig.page_count;
                    return temp_list.slice(index, index+PageConfig.page_count);
                } else {
                    return temp_list;
                }
            } else {
                return list;
            }
        };
        
        $scope.orderbychange  = function(mode)
        {
            if($scope.order_by_mode.name != mode)
            {
                $scope.order_by_mode.name = mode;
                $scope.order_by_mode.sort = false;
            }
            else
            {
                $scope.order_by_mode.sort = !$scope.order_by_mode.sort
            }
        }

        var dog = {
            sleep: $scope.refresh_frequency,
            bark: function(feed, next){
                if($scope.area_no && $scope.area_no != ''){
                    materialDashboardInfoGet(next, next == undefined);
                }else{
                    next();
                }
            }            
        };

        var refresh_timer;
        function ErrorHandler(msg, isShowLoading, callback){
            if($scope){
                $scope.$root.showAlert(msg);
                if(!isShowLoading){
                    $scope.disconnection = true;
                    $scope.refresh =  function(){
                        $scope.disconnection = false;
                        $timeout.cancel(refresh_timer);
                        refresh_timer = undefined;
                        callback();
                    };
                    if(refresh_timer == undefined){
                        refresh_timer = $timeout(function(){
                            $scope.refresh();
                        }, $scope.refresh_frequency*1000);
                    }
                }
            }
        }

        function pageNumberInfoGet(content, callback){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                content : content,
                success : function(data){
                    if (callback)
                        callback(data.page_number_info_get);
                }
            });
        }

        //生產批資訊查詢
        function materialDashboardInfoGet(callback, isShowLoading){
            //測試資料
            var data = {};
            /*data.material_info_detail = [{
                demand_time: '2019-04-09 12:00:00',
                mo_no: 'MO-2019040901',
                op_no: '1001',
                machine_no: 'EE01',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '100',
                demand_labor: 'DS',
                demand_source: '材料倉',
                wip_qty: '10',
                feeding_qty: '20'
            },
            {
                demand_time: '2019-04-09 12:00:01',
                mo_no: 'MO-2019040902',
                op_no: '1002', 
                machine_no: 'EE02',
                position_no: 'N/A',
                material_no: 'MAT-2019040902',
                demand_qty: '200',
                demand_labor: 'DS1',
                demand_source: '材料倉1',
                wip_qty: '20',
                feeding_qty: '300'
            },
            {
                demand_time: '2019-04-09 12:00:02',
                mo_no: 'MO-2019040903',
                op_no: '1003',
                machine_no: 'EE03',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '300',
                demand_labor: 'DS2',
                demand_source: '材料倉2',
                wip_qty: '30',
                feeding_qty: '40'
            },
            {
                demand_time: '2019-04-09 12:00:02',
                mo_no: 'MO-2019040903',
                op_no: '1003',
                machine_no: 'EE03',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '300',
                demand_labor: 'DS2',
                demand_source: '材料倉2',
                wip_qty: '30',
                feeding_qty: '40'
            },            
            {
                demand_time: '2019-04-09 12:00:02',
                mo_no: 'MO-2019040903',
                op_no: '1003',
                machine_no: 'EE03',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '300',
                demand_labor: 'DS2',
                demand_source: '材料倉2',
                wip_qty: '30',
                feeding_qty: '40'
            },
            {
                demand_time: '2019-04-09 12:00:02',
                mo_no: 'MO-2019040903',
                op_no: '1003',
                machine_no: 'EE03',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '300',
                demand_labor: 'DS2',
                demand_source: '材料倉2',
                wip_qty: '30',
                feeding_qty: '40'
            },
            {
                demand_time: '2019-04-09 12:00:02',
                mo_no: 'MO-2019040903',
                op_no: '1003',
                machine_no: 'EE03',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '300',
                demand_labor: 'DS2',
                demand_source: '材料倉2',
                wip_qty: '30',
                feeding_qty: '40'
            },
            {
                demand_time: '2019-04-09 12:00:02',
                mo_no: 'MO-2019040903',
                op_no: '1003',
                machine_no: 'EE03',
                position_no: 'N/A',
                material_no: 'MAT-2019040901',
                demand_qty: '300',
                demand_labor: 'DS2',
                demand_source: '材料倉2',
                wip_qty: '30',
                feeding_qty: '40'
            }];*/
            // if (callback)
            //     callback(data);
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_MAT.material_dashboard_info_get',
                // uri : 'ServicesSTD.Module_SYS.favourite_machine_info_get',
                content : {
                    area_no: $scope.area_no, 
                    type: '1'
                },
                // content: {
                //     master_no:config.cache.account,
                //     master_type:'0',
                //     get_employee_data:'Y'
                // },
                success : function(data) {
                    $scope.material_info_detail = data.material_info_detail;
                    if (callback)
                        callback();
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        materialDashboardInfoGet(callback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        materialDashboardInfoGet(callback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        //物料看板確認作業
        function materialDashboardConfirmProcess(content, callback){
            // $rootScope.showToast('確認成功');
            // if (callback)
            //     callback();
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_MAT.material_dashboard_confirm_process',
                content : content,
                success : function(data, response) {
                    $rootScope.showToast(response.Message);
                    if (callback)
                        callback(data);
                }
            });
        }
    }
];});
